package com.imooc.security.browser.controller;

import com.imooc.security.browser.pojo.SimpleResult;
import com.imooc.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 当需要身份认证时，跳转到这里。保证原始发起的URL请求一定要是带.html结尾的
 * @author JackYang
 * @description:
 * @create: 2020/6/15 12:47
 */
@RestController
@RequestMapping("/authentication")
public class BrowserSecurityController {
    
    @Autowired
    private SecurityProperties securityProperties;
    
    private RequestCache requestCache=new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();
    
    Logger logger=LoggerFactory.getLogger(getClass());
    
    @GetMapping("/require")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public SimpleResult requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SavedRequest savedRequest=requestCache.getRequest(request, response);
        if (savedRequest!=null){
            //引发跳转的请求
            String redirectUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转的请求是: {}", redirectUrl);
            if(StringUtils.endsWithIgnoreCase(redirectUrl,".html")){
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
            }
        }
        return new SimpleResult("不是html方式。。。。");
    }
}
